package com.henry.chatkit.messages

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.henry.chatkit.*
import com.henry.chatkit.utils.BackgroundTasks
import com.henry.chatkit.weight.PopupList
import java.util.*

open class MessageLayout : MessageLayoutUI {

    private var mLoading = true

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    override fun onInterceptTouchEvent(e: MotionEvent?): Boolean {
        if (e!!.action == MotionEvent.ACTION_DOWN) {
            val child = findChildViewUnder(e.x, e.y)
            if (child == null) {
                mEmptySpaceClickListener?.onClick()
            } else if (child is ViewGroup) {
                val count = child.childCount
                val x = e.rawX
                val y = e.rawY
                var touchChild: View? = null
                for (i in count - 1 downTo 0) {
                    val innerChild = child.getChildAt(i)
                    val position = IntArray(2)
                    innerChild.getLocationOnScreen(position)
                    if (x >= position[0] && x <= position[0] + innerChild.measuredWidth && y >= position[1] && y <= position[1] + innerChild.measuredHeight) {
                        touchChild = innerChild
                        break
                    }
                }
                if (touchChild == null) {
                    mEmptySpaceClickListener?.onClick()
                }
            }
        }
        return super.onInterceptTouchEvent(e)
    }

    override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
        super.onScrollChanged(l, t, oldl, oldt)
    }

    override fun onScrollStateChanged(state: Int) {
        super.onScrollStateChanged(state)
        if (!mLoading) return

        if (state == SCROLL_STATE_IDLE) {
            if (mHandler != null) {
                val layoutManager = layoutManager as LinearLayoutManager?
                val firstPosition = layoutManager!!.findFirstCompletelyVisibleItemPosition()
                val lastPosition = layoutManager.findLastCompletelyVisibleItemPosition()
                if (firstPosition == 0 && lastPosition - firstPosition + 1 < adapter!!.itemCount) {
                    if (adapter is MessageListAdapter) {
                        (adapter as MessageListAdapter?)!!.showLoading()
                    }
                    mHandler!!.loadMore()
                }
            }
        }
    }

    override fun postSetAdapter(adapter: MessageListAdapter?) {
        mOnItemClickListener?.let { mAdapter?.setOnItemClickListener(it) }
    }

    fun scrollToEnd() {
        BackgroundTasks.getInstance()?.runOnUiThread {
            if (adapter != null) {
                if (adapter!!.itemCount - 1 > 0) {
                    scrollToPosition(adapter!!.itemCount - 1)
                }
            }
        }
    }

    fun getEmptySpaceClickListener(): OnEmptySpaceClickListener? {
        return mEmptySpaceClickListener
    }

    fun setEmptySpaceClickListener(emptySpaceClickListener: OnEmptySpaceClickListener?) {
        mEmptySpaceClickListener = emptySpaceClickListener
    }

    fun getLoadMoreHandler(): OnLoadMoreHandler? {
        return mHandler
    }

    fun setLoadMoreMessageHandler(handler: OnLoadMoreHandler) {
        mHandler = handler
    }

    fun setPopActionClickListener(listener: OnPopActionClickListener) {
        mOnPopActionClickListener = listener
    }

    private fun initPopActions(msg: MessageInfo?) {
        if (msg == null) {
            return
        }
        val actions: MutableList<PopMenuAction> = ArrayList()
        var action = PopMenuAction()
        if (msg.msgType == MessageType.TEXT) {
            action.actionName = "复制"
            action.actionClickListener = object : PopActionClickListener {
                override fun onActionClick(position: Int, data: Any?) {
                    mOnPopActionClickListener?.onCopyClick(position, data as MessageInfo?)
                }
            }
            actions.add(action)
        }

        // 可撤回
        if (msg.status == MessageStatus.REVOKE) {
            action = PopMenuAction()
            action.actionName = "撤回"
            action.actionClickListener = object : PopActionClickListener {
                override fun onActionClick(position: Int, data: Any?) {
                    mOnPopActionClickListener?.onRevokeMessageClick(position, data as MessageInfo?)
                }
            }
            actions.add(action)
        }

        if (msg.isSelf) { // 重发

            if (msg.status == MessageStatus.SEND_FAIL) {
                action = PopMenuAction()
                action.actionName = "重发"
                action.actionClickListener = object : PopActionClickListener {
                    override fun onActionClick(position: Int, data: Any?) {
                        mOnPopActionClickListener?.onSendMessageClick(msg, true)
                    }
                }
                actions.add(action)
            }
        }

        mPopActions.clear()
        mPopActions.addAll(actions)
        mPopActions.addAll(mMorePopActions)

    }

    fun showItemPopMenu(index: Int, messageInfo: MessageInfo?, view: View?) {
        initPopActions(messageInfo)
        if (mPopActions.size == 0) {
            return
        }
        val popupList = PopupList(context)
        val mItemList = mutableListOf<String>()
        for (action in mPopActions) {
            action.actionName?.let { mItemList.add(it) }
        }
        popupList.show(view, mItemList, object : PopupList.PopupListListener {
            override fun showPopupList(
                adapterView: View?,
                contextView: View?,
                contextPosition: Int
            ): Boolean {
                return true
            }

            override fun onPopupListClick(contextView: View?, contextPosition: Int, position: Int) {
                val action = mPopActions[position]
                action.actionClickListener?.onActionClick(index, messageInfo)
            }
        })

        postDelayed({
            popupList.hidePopupListWindow()
        }, 10000) // 10s后无操作自动消失

    }

    fun setLoading(loading: Boolean) {
        mLoading = loading
    }

}